﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharpSphinx.Util
{


    /// <summary>
    /// * Provides a simple object cache.
    /// <p>Object stored in cache must properly implement {@link Object#hashCode hashCode} and {@link Object#equals equals}.
    /// <p><strong>Note that this class is not synchronized.</strong>
    /// If multiple threads access a cache concurrently, and at least one of
    /// the threads modifies the cache, it <i>must</i> be synchronized externally.
    /// This is typically accomplished by synchronizing on some object that
    /// naturally encapsulates the cache.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Cache<T>
    {

        private Dictionary<T, T> Map = new Dictionary<T, T>();


        private int hits = 0;


        public T Cache(T obj)
        {
            T ret;
            Map.TryGetValue(obj, out ret);

            if (ret == null)
            {
                Map.Add(obj, obj);
            }
            else
            {
                hits++;
            }
            return ret;
        }


        public int Hits
        {
            get
            {
                return hits; 
            }
        }

        public int Misses
        {
            get
            {
                return Map.Count;
            }
        }
    }
}
